package com.mr.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/**
 * Class: RateLimiterFilter
 * User (作者):MRui
 * TODO (描述)：限流拦截器（短信轰炸限流，令牌桶的方式）
 * Date 2018-11-15 22:00
 */
@Component
public class RateLimiterFilter extends ZuulFilter {
    // 100:每秒钟放100个令牌
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
    //拦截器类型：前置
    @Override
    public String filterType() {
        return PRE_TYPE;
    }
    //拦截器顺序 在SERVLET_DETECTION_FILTER_ORDER前面
    @Override
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER - 1;
    }
    //是否启用拦截器
    @Override
    public boolean shouldFilter() {
        return true;
    }
    //拦截器内容
    @Override
    public Object run() throws ZuulException {
        //取令牌
        if(!RATE_LIMITER.tryAcquire()){
            //如果取不到则处理内容
            System.out.println("吃了吗?");
        }

        return null;
    }
}
